import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class FlutterTextFile extends StatefulWidget {
  ///输入框宽度
  double width;

  ///输入框高度
  double height;

  ///左侧图标 默认搜索图标
  Widget leftIcon;

  ///右侧图标 默认清除图标
  Widget rightIcon;

  ///左侧图标大小  设置leftIcon后失效
  double leftSize;

  ///右侧图标大小 设置rightIcon后失效
  double rightSize;

  ///边框
  Decoration decoration;

  ///圆角
  final BorderRadiusGeometry borderRadius;

  ///是否显示左侧图标
  bool isLeftIcon;

  ///是否显示右侧图标
  bool isRightIcon;

  ///输入事件回调
  ValueChanged<String> onChanged;

  ///回车事件回调
  ValueChanged<String> submitChanged;
  

//  以下参数 和 TextFild的参数一致

  final TextStyle style;

  final TextEditingController controller;

  /// {@macro flutter.widgets.editableText.strutStyle}
  final StrutStyle strutStyle;

  /// {@macro flutter.widgets.editableText.textAlign}
  final TextAlign textAlign;

  /// {@macro flutter.material.inputDecorator.textAlignVertical}
  final TextAlignVertical textAlignVertical;

  /// {@macro flutter.widgets.editableText.textDirection}
  final TextDirection textDirection;

  /// {@macro flutter.widgets.editableText.autofocus}
  final bool autofocus;

  /// {@macro flutter.widgets.editableText.obscureText}
  final bool obscureText;

  /// {@macro flutter.widgets.editableText.autocorrect}
  final bool autocorrect;

  /// {@macro flutter.services.textInput.enableSuggestions}
  final bool enableSuggestions;

  /// {@macro flutter.widgets.editableText.maxLines}
  final int maxLines;

  /// {@macro flutter.widgets.editableText.minLines}
  final int minLines;

  /// {@macro flutter.widgets.editableText.cursorWidth}
  final double cursorWidth;

  /// {@macro flutter.widgets.editableText.cursorRadius}
  final Radius cursorRadius;

  final Color cursorColor;

  final Brightness keyboardAppearance;

  /// {@macro flutter.widgets.editableText.scrollPadding}
  final EdgeInsets scrollPadding;

  /// {@macro flutter.widgets.editableText.enableInteractiveSelection}
  final bool enableInteractiveSelection;

  /// {@macro flutter.widgets.scrollable.dragStartBehavior}
  final DragStartBehavior dragStartBehavior;

  /// {@macro flutter.rendering.editable.selectionEnabled}
  bool get selectionEnabled => enableInteractiveSelection;

  final GestureTapCallback onTap;

  final InputCounterWidgetBuilder buildCounter;

  /// {@macro flutter.widgets.edtiableText.scrollPhysics}
  final ScrollPhysics scrollPhysics;

  /// {@macro flutter.widgets.editableText.scrollController}
  final ScrollController scrollController;

  /// {@macro flutter.widgets.editableText.expands}
  final bool expands;

  /// {@macro flutter.widgets.editableText.textCapitalization}
  final TextCapitalization textCapitalization;

  final TextInputAction textInputAction;

  final bool maxLengthEnforced;

  /// {@macro flutter.widgets.editableText.readOnly}
  final bool readOnly;

  /// {@macro flutter.widgets.editableText.showCursor}
  final bool showCursor;
  final FocusNode focusNode;

  /// {@macro flutter.widgets.editableText.inputFormatters}
  final List<TextInputFormatter> inputFormatters;

  /// {@macro flutter.widgets.editableText.onEditingComplete}
  final VoidCallback onEditingComplete;

  /// {@macro flutter.widgets.editableText.keyboardType}
  final TextInputType keyboardType;
  final int maxLength;

  /// Defaults to false.
  final bool alignLabelWithHint;

  final ToolbarOptions toolbarOptions;
  final InputBorder enabledBorder;
  final InputBorder errorBorder;
  final int errorMaxLines;
  final TextStyle errorStyle;
  final String errorText;
  final bool hasFloatingPlaceholder;

  /// Defaults to false.
  final bool isDense;

  final bool isCollapsed;
  final Widget prefixIcon;
  final Widget prefix;
  final TextStyle prefixStyle;
  final Widget suffixIcon;

  final Widget suffix;

  final String suffixText;

  final TextStyle suffixStyle;

  final String counterText;

  final Widget counter;

  final TextStyle counterStyle;

  final bool filled;

  final Color fillColor;
  final Color focusColor;

  final Color hoverColor;
  final InputBorder focusedErrorBorder;
  final InputBorder focusedBorder;
  final InputBorder disabledBorder;
  final int helperMaxLines;

  final bool enabled;
  final String helperText;
  final int hintMaxLines;
  final String hintText;

  final TextStyle hintStyle;
  final String labelText;

  final TextStyle labelStyle;
  final String prefixText;
  final Widget icon;

  final TextStyle helperStyle;

  final String semanticCounterText;

  FlutterTextFile({
    Key key,
    this.width = 200,
    this.height = 40,
    this.rightIcon,
    this.leftIcon,
    this.leftSize = 30,
    this.rightSize = 25,
    this.decoration,
    this.borderRadius,
    this.controller,
    this.onChanged,
    this.submitChanged,
    this.isLeftIcon = true,
    this.isRightIcon = true,
    this.style,
    this.textDirection,
    this.textAlignVertical,
    this.textAlign = TextAlign.start,
    this.strutStyle,
    this.obscureText = false,
    this.minLines,
    this.maxLines = 1,
    this.enableSuggestions = true,
    this.autofocus = false,
    this.autocorrect = true,
    this.cursorWidth = 2.0,
    this.scrollPadding = const EdgeInsets.all(20.0),
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection = true,
    this.onTap,
    this.buildCounter,
    this.scrollController,
    this.scrollPhysics,
    this.inputFormatters,
    this.expands = false,
    this.textCapitalization = TextCapitalization.none,
    TextInputType keyboardType,
    ToolbarOptions toolbarOptions,
    this.cursorColor,
    this.cursorRadius,
    this.keyboardAppearance,
    this.textInputAction,
    this.readOnly = false,
    this.maxLengthEnforced = true,
    this.showCursor,
    this.focusNode,
    this.onEditingComplete,
    this.maxLength = 1,
    this.enabled = true,
    this.alignLabelWithHint,
    this.counter,
    this.counterStyle,
    this.counterText,
    this.disabledBorder,
    this.enabledBorder,
    this.errorBorder,
    this.errorMaxLines,
    this.errorStyle,
    this.errorText,
    this.fillColor,
    this.filled,
    this.suffixText,
    this.focusColor,
    this.focusedBorder,
    this.focusedErrorBorder,
    this.hasFloatingPlaceholder,
    this.hoverColor,
    this.isCollapsed,
    this.isDense,
    this.prefixStyle,
    this.prefix,
    this.prefixIcon,
    this.semanticCounterText,
    this.suffix,
    this.suffixIcon,
    this.suffixStyle,
    this.helperMaxLines,
    this.helperStyle,
    this.helperText,
    this.hintMaxLines,
    this.hintStyle,
    this.hintText,
    this.icon,
    this.labelStyle,
    this.labelText,
    this.prefixText,
  })  : assert(textAlign != null),
        assert(readOnly != null),
        assert(autofocus != null),
        assert(obscureText != null),
        assert(autocorrect != null),
        assert(enableSuggestions != null),
        assert(enableInteractiveSelection != null),
        assert(maxLengthEnforced != null),
        assert(scrollPadding != null),
        assert(dragStartBehavior != null),
        assert(maxLines == null || maxLines > 0),
        assert(minLines == null || minLines > 0),
        assert(
          (maxLines == null) || (minLines == null) || (maxLines >= minLines),
          'minLines can\'t be greater than maxLines',
        ),
        assert(expands != null),
        assert(
          !expands || (maxLines == null && minLines == null),
          'minLines and maxLines must be null when expands is true.',
        ),
        assert(!obscureText || maxLines == 1,
            'Obscured fields cannot be multiline.'),
        assert(maxLength == null ||
            maxLength == TextField.noMaxLength ||
            maxLength > 0),
        keyboardType = keyboardType ??
            (maxLines == 1 ? TextInputType.text : TextInputType.multiline),
        toolbarOptions = toolbarOptions ??
            (obscureText
                ? const ToolbarOptions(
                    selectAll: true,
                    paste: true,
                  )
                : const ToolbarOptions(
                    copy: true,
                    cut: true,
                    selectAll: true,
                    paste: true,
                  )),
        super(key: key);

  @override
  _FlutterTextFileState createState() => _FlutterTextFileState();
}

class _FlutterTextFileState extends State<FlutterTextFile> {
  TextEditingController _controller = TextEditingController();
  bool _isText = false;

  ///初始化时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.controller != null) {
      setState(() {
        _controller = widget.controller;
      });
    }
  }

  ///更新组件时
  @override
  void didUpdateWidget(FlutterTextFile oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if (widget.controller != null) {
      setState(() {
        _controller = widget.controller;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,

      decoration: widget.decoration ?? BoxDecoration(
        border: Border.all(color: Colors.indigo),
      ),
      child: Row(
        children: <Widget>[
          ///输入框前面的 例如搜索图标
          Offstage(
            offstage: !widget.isLeftIcon,
            child: Container(
              height: widget.height,
              child: widget.leftIcon ??
                  Icon(
                    Icons.search,
                    size: widget.leftSize,
                    color: Colors.indigo,
                  ),
              margin: EdgeInsets.only(right: 6, left: 8),
//              padding: EdgeInsets.only(right: 4),
//            左侧图标分割线
//              decoration: BoxDecoration(
//                  border: Border(
//                      right: BorderSide(color: Colors.indigo)
//                  )
//              ),
            ),
          ),

          ///输入框主体
          Expanded(
            child: Container(
              padding: EdgeInsets.only(left: widget.isLeftIcon ?0:10,right: widget.isRightIcon ?0:10),
              height: widget.height,
              child: TextField(
                controller: _controller,
                key: widget.key,
                readOnly: widget.readOnly,
                showCursor: widget.showCursor,
                focusNode: widget.focusNode,
                keyboardType: widget.keyboardType,
                textInputAction: widget.textInputAction,
                textCapitalization: widget.textCapitalization,
                style: widget.style,
                strutStyle: widget.strutStyle,
                textAlign: widget.textAlign,
                textDirection: widget.textDirection,
                autofocus: widget.autofocus,
                obscureText: widget.obscureText,
                autocorrect: widget.autocorrect,
                enableSuggestions: widget.enableSuggestions,
                maxLines: widget.maxLines,
                minLines: widget.minLines,
                expands: widget.expands,
                onEditingComplete: widget.onEditingComplete,
                inputFormatters: widget.inputFormatters,
                cursorWidth: widget.cursorWidth,
                cursorRadius: widget.cursorRadius,
                cursorColor: widget.cursorColor,
                scrollPadding: widget.scrollPadding,
                keyboardAppearance: widget.keyboardAppearance,
                enableInteractiveSelection: widget.enableInteractiveSelection,
                dragStartBehavior: widget.dragStartBehavior,
                scrollController: widget.scrollController,
                scrollPhysics: widget.scrollPhysics,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(top: -9),
                  alignLabelWithHint: widget.alignLabelWithHint,
                  enabledBorder: widget.enabledBorder,
                  errorBorder: widget.errorBorder,
                  errorMaxLines: widget.errorMaxLines,
                  errorStyle: widget.errorStyle,
                  errorText: widget.errorText,
                  counter: widget.counter,
                  counterStyle: widget.counterStyle,
                  counterText: widget.counterText,
                  disabledBorder: widget.disabledBorder,
                  filled: widget.filled,
                  focusedBorder: widget.focusedBorder,
                  focusedErrorBorder: widget.focusedErrorBorder,
                  hasFloatingPlaceholder: widget.hasFloatingPlaceholder,
                  helperMaxLines: widget.helperMaxLines,
                  helperStyle: widget.helperStyle,
                  helperText: widget.helperText,
                  hintMaxLines: widget.hintMaxLines,
                  hintStyle: widget.hintStyle,
                  hintText: widget.hintText,
                  hoverColor: widget.hoverColor,
                  isDense: widget.isDense,
                  labelStyle: widget.labelStyle,
                  labelText: widget.labelText,
                  prefix: widget.prefix,
                  prefixIcon: widget.prefixIcon,
                  prefixStyle: widget.prefixStyle,
                  prefixText: widget.prefixText,
                  semanticCounterText: widget.semanticCounterText,
                  suffixStyle: widget.suffixStyle,
                  fillColor: widget.fillColor,
                  focusColor: widget.focusColor,
                  suffix: widget.suffix,
                  suffixIcon: widget.suffixIcon,
                  icon: widget.icon,
                  suffixText: widget.suffixText,
                  enabled: widget.enabled,
                ),
                onChanged: (_) {
                  widget.onChanged(_);
                  if (_ != "" && widget.isRightIcon) {
                    setState(() {
                      _isText = true;
                    });
                  } else {
                    setState(() {
                      _isText = false;
                    });
                  }
                },
                onSubmitted: (_) {
                  widget.submitChanged(_);
                },
              ),
            ),
          ),

          ///内容后面的图标 例如清除按钮
          Offstage(
            offstage: !_isText,
            child: Container(
              height: widget.height,
              child: GestureDetector(
                child: widget.rightIcon ??
                    Icon(
                      Icons.highlight_off,
                      color: Colors.red,
                      size: widget.rightSize,
                    ),
                onTap: () {
                  print("clean");
                  setState(() {
                    _controller.clear();
                    _isText = false;
                  });
                },
              ),
              margin: EdgeInsets.only(right: 10, left: 4),
            ),
          )
        ],
      ),
    );
  }
}
